<?php

namespace app\bsadmin\controller;

use app\common\model\WebsiteTemplate;
use app\common\model\WechatTemplate;
use helper\URL;
use helper\Wechat as WechatHelper;
use think\cache\driver\Redis;
use think\Exception;
use think\facade\View;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;
use app\bsadmin\model\Config as ConfigModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\model\PushMessage as PushMessageModel;
use app\common\model\PushMessageContent as PushMessageContentModel;
use app\common\model\PushQueue as PushQueueModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserWx as UserWxModel;
use app\common\model\InitiativePush as InitiativePushModel;
use XYCms\Sms;
use XYCms\Email;
use XYCms\Im as XYCMSIm;
use XYCms\WechatPush;
class Message extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['msg.uid', '=', $G['key']];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['msg.status', '=', $G['status']];
            }
            if ($G['is_read'] != 'all') {
                $where[] = ['msg.is_read', '=', $G['is_read']];
            }
            $Data = PushMessageModel::alias('msg')->where($where)
                ->join('user_info user_info', 'user_info.uid = msg.uid')
                ->field('msg.*,user_info.nickname,user_info.headimg')
                ->order('msg.id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v->delete_time = $v['delete_time'] ? date('Y-m-d H:i', $v['delete_time']) : '';
                    $v->nickname = base64_decode($v['nickname']);
                    $v->headimg = config('web.imgurl') . $v['headimg'];
                    $v->content = '';
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $msgType = StatusAliasModel::getSelect('message/type');
            View::assign('msgType', $msgType);
            return View::fetch();
        }
    }
    public function queueList()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['status'] != 'all') {
                $where[] = ['msg.status', '=', $G['status']];
            }
            $Data = PushQueueModel::where($where)
                ->withoutField('content')
                ->order('status asc,id desc')->paginate($G['pageSize'])->each(function ($v) {
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function pushList()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['msg.uid', '=', $G['key']];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['msg.status', '=', $G['status']];
            }
            if ($G['type'] != 'all') {
                $where[] = ['msg.type', '=', $G['type']];
            }
            $Data = PushTaskModel::alias('msg')->where($where)
                ->join('user_info user_info', 'user_info.uid = msg.uid', 'LEFT')
                ->field('msg.*,user_info.nickname,user_info.headimg')
                ->order('msg.id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v->nickname = base64_decode($v['nickname']);
                    $v->headimg = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                    $v->data = json_decode($v['data'], true);
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            $msgType = StatusAliasModel::getSelect('message/type');
            View::assign('msgType', $msgType);
            return View::fetch();
        }
    }
    public function sendMessage()
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'crowd'             => 'require',
                'title'             => 'require',
                'desc'              => 'length:0,50',
                'content'           => 'require',
            ];
            $msg  =   [
                'crowd.require'     => '请选择接收人群',
                'title.require'     => '请输入标题',
                'desc.length'       => '描述请控制在50个字以内',
                'content.require'   => '请输入内容',
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            if ($D['crowd'] == 'appoint') {
                $TaskList = [];
                $msgData = json_encode(['title' => $D['title'], 'desc' => $D['desc'], 'content' => $D['content']], JSON_UNESCAPED_UNICODE);
                foreach ($D['user_list'] as $k => $v) {
                    $TaskList[] = [
                        'uid'       =>  $v,
                        'client'    =>  $D['client'] ? implode(',', $D['client']) : null,
                        'event'     =>  'sendSiteMsg',
                        'data'      =>  $msgData
                    ];
                }
                $PushTaskModel = new PushTaskModel;
                if ($PushTaskModel->saveAll($TaskList)) {
                    return $this->ajaxReturn('发送成功');
                } else {
                    return $this->ajaxReturn('保存失败，请重试', -100);
                }
            } else {
                $sum = 0;
                switch ($D['crowd']) {
                    case 'all':
                        $sum = UserModel::where(['status' => 1])->count();
                        break;
                    case 'company':
                        $sum = UserInfoModel::where(['role_type' => 1])->count();
                        break;
                    case 'personal':
                        $sum = UserInfoModel::where(['role_type' => 0])->count();
                        break;
                    case 'mp':
                        $sum = UserWxModel::where(['subscribe' => 1])->whereNotNull('wx_openid')->count();
                        break;
                    case 'mobile':
                        $sum = UserModel::where(['status' => 1])->whereNotNull('mobile')->count();
                        break;
                    case 'email':
                        $sum = UserModel::where(['status' => 1])->whereNotNull('email')->count();
                        break;
                }
                $PushQueueModel = new PushQueueModel;
                $PushQueueModel->crowd      =   $D['crowd'];
                $PushQueueModel->client     =   $D['client'] ? implode(',', $D['client']) : null;
                $PushQueueModel->title      =   $D['title'];
                $PushQueueModel->desc       =   $D['desc'];
                $PushQueueModel->content    =   $D['content'];
                $PushQueueModel->sum        =   $sum;
                if ($PushQueueModel->save()) {
                    return $this->ajaxReturn('创建队列成功');
                } else {
                    return $this->ajaxReturn('保存失败，请重试', -100);
                }
            }
        } else {
            return View::fetch();
        }
    }
    public function getMessageContent($id)
    {
        $Find = PushMessageContentModel::where(['mid' => $id])->find();
        if ($Find) {
            return $this->ajaxReturn('', 0, $Find);
        } else {
            return $this->ajaxReturn('消息不存在', -100);
        }
    }
    public function setStatus($id, $status)
    {
        $Find = PushMessageModel::where(['id' => $id])->find();
        if ($Find) {
            $Find->status = $status;
            if ($Find->save()) {
                return $this->ajaxReturn();
            } else {
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            return $this->ajaxReturn('消息不存在', -100);
        }
    }
    public function setIsRead($id, $is_read)
    {
        $Find = PushMessageModel::where(['id' => $id])->find();
        if ($Find) {
            $Find->is_read = $is_read;
            if ($Find->save()) {
                return $this->ajaxReturn();
            } else {
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            return $this->ajaxReturn('消息不存在', -100);
        }
    }
    public function setMessage()
    {
        $Data = ConfigModel::getList([['ctype', 'in', ['xycms_message', 'xy_getui', 'xy_email']]]);
        View::assign('Data', $Data);
        View::assign('ctype', 'xycms_message');
        return View::fetch('setting/message');
    }
    public function sendSmsMessage()
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'mobile'            => 'require|mobile',
                'content'           => 'require',
            ];
            $msg  =   [
                'mobile.require'    => '请输入接收人',
                'mobile.mobile'     => '手机号错误',
                'content.require'   => '请输入内容',
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            try {
                $Sms = new Sms;
                $Sms->phone = $D['mobile'];
                $Sms->msg = $D['content'];
                $ret = $Sms->sendSms();
                return $this->ajaxReturn('发送成功');
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(), -100);
            }
        } else {
            return View::fetch();
        }
    }
    public function sendEmail()
    {
        if (request()->isPost()) {
            $D = request()->post();
            $rule =   [
                'email'             => 'require|email',
                'title'             => 'require',
                'content'           => 'require',
            ];
            $msg  =   [
                'email.require'    => '请输入接收人',
                'email.email'     => '邮箱错误',
                'title.require'    => '请输入标题',
                'content.require'   => '请输入内容',
            ];
            $Validate = Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if (!$result) {
                return $this->ajaxReturn($Validate->getError(), -100);
            }
            try {
                $Email = new Email;
                $name = config('web.name');
                $ret = $Email->init($D['email'], $name, $D['title'], $D['content']);
                if ($ret === true) {
                    return $this->ajaxReturn('发送成功');
                } else {
                    return $this->ajaxReturn($ret, -100);
                }
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(), -100);
            }
        } else {
            return View::fetch();
        }
    }
    /*
        try {
            $imObj=new XYCMSIm;
            $search=[
                // 分页
                'page'=>1,
                // 每页数目
                'list_rows'=>10,
                // 发送者
                'senduid'=>'',
                // 接收者
                'touid'=>'',
                // 消息类型（text:文本，img:图片，exchange_wechat:交换微信，exchange_mobile:交换手机号，resume:发送简历）
                'type'=>'',
                // 消息内容（模糊搜索）
                'content'=>''
            ];
            $Data=$imObj->getHistoryMessage($search);
            p($Data);
        } catch (\think\Exception $e) {
            return $this->ajaxReturn($e->getMessage(),-100);
        }
        die;
    */
    public function getHistoryMessage()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $search = [];
            if (!empty($G['page'])) {
                $search['page'] = $G['page'];
            }
            if (!empty($G['pageSize'])) {
                $search['list_rows'] = $G['pageSize'];
            }
            if (!empty($G['senduid'])) {
                $search['senduid'] = $G['senduid'];
            }
            if (!empty($G['touid'])) {
                $search['touid'] = $G['touid'];
            }
            if (!empty($G['type'])) {
                $search['type'] = $G['type'];
            }
            if (!empty($G['key'])) {
                $search['content'] = $G['key'];
            }


            // $search = [
            //     // 分页
            //     'page' => 1,
            //     // 每页数目
            //     'list_rows' => 10,
            //     // 发送者
            //     'senduid' => '',
            //     // 接收者
            //     'touid' => '',
            //     // 消息类型（text:文本，img:图片，exchange_wechat:交换微信，exchange_mobile:交换手机号，resume:发送简历）
            //     'type' => '',
            //     // 消息内容（模糊搜索）
            //     'content' => ''
            // ];



            try {
                $imObj = new XYCMSIm;
                $data = $imObj->getHistoryMessage($search);
                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['send_info'] = UserInfoModel::alias('info')
                        ->where(['info.uid' => $value['senduid']])
                        ->join('company com', 'com.uid=info.uid', 'LEFT')
                        ->join('resume res', 'res.uid=info.uid', 'LEFT')
                        ->field(['info.nickname', 'info.headimg', 'com.title', 'res.name'])
                        ->withAttr('nickname', function($val,$row){
                            return base64_decode($val);
                        })
                        ->withAttr('headimg', function($val,$row){
                            return config('web.imgurl') . $val;
                        })
                        ->find();
                        $data['data'][$key]['to_info'] = UserInfoModel::alias('info')
                        ->where(['info.uid' => $value['touid']])
                        ->join('company com', 'com.uid=info.uid', 'LEFT')
                        ->join('resume res', 'res.uid=info.uid', 'LEFT')
                        ->field(['info.nickname', 'info.headimg', 'com.title', 'res.name'])
                        ->withAttr('nickname', function($val,$row){
                            return base64_decode($val);
                        })
                        ->withAttr('headimg', function($val,$row){
                            return config('web.imgurl') . $val;
                        })
                        ->find();
                }
                return $this->ajaxReturn('获取成功', 0, $data);
            } catch (\think\Exception $e) {
                return $this->ajaxReturn($e->getMessage(), -100);
            }
        } else {
            return View::fetch('im/history');
        }
    }

    /**
     * @Notes:公众号模板推送（直接编辑内容推送到公众号）
     * @Author: hhm <huanghemao@exinyun.com>
     * @DateTime: 2022/2/25 0025 下午 18:52
     */
    public function templateNotify(){
        if (request()->post()){
            $D=request()->post();
            if (empty($D['form']['title']))
                return $this->ajaxReturn('标题不能为空',-100);
            if (empty($D['template_id']))
                return $this->ajaxReturn('请选择推送模板',-100);
            if (empty($D['form']['toUserType']))
                return $this->ajaxReturn('请选择推送对象',-100);
            foreach ($D['data'] as $k=> $v){
                if (!empty($v['name'])){
                    $data[$v['name']]=[
                        "value" => $v['value']??'',
                        "color" => $v['color']??''
                    ];
                }else{
                    $data['keyword'.($k)]=[
                        "value"=>$v['value'],
                        "color" => $v['color']
                    ];
                }
            }
            $Initiative=new InitiativePushModel();
            $Initiative->wt_id=$D['template_id'];
            $Initiative->tpl_title=$D['tpl_title'];
            $Initiative->data=json_encode($data);
            $Initiative->to_user_num=$D['form']['to_user_num'];
            $Initiative->title=$D['form']['title'];
            $Initiative->to_user_type=$D['form']['toUserType'];
            $Initiative->user_group=!empty($D['form']['fansGroupTag'])?implode(",",$D['form']['fansGroupTag']):"";
            $Initiative->save();
            $sendData=[
                'template_id'=>$D['template_id'],
                'sendData'=>$data,
                'toWhereType'=>$D['form']['toWhereType'],//详情跳转小程序还是链接
                'url'=>$D['form']['url']??$D['form']['standbyUrl'],
                'appid'=>$D['form']['appId']??null,
                'pagepath'=>$D['form']['pagePath']??null,
                'to_user_type'=>$D['form']['toUserType'], //发送对象，全部粉丝或者标签组
                'id'=>$Initiative->id
            ];
            $redisConfig=config('cache.stores.redis');
            $redis=new Redis($redisConfig);
            $ret=$redis->lPush($redisConfig['prefix']."WechatPush-independentTask", json_encode($sendData,JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES));
            if($ret){
                return $this->ajaxReturn('提交成功正在发送', 0);
            }else{
                throw new Exception('插入缓存失败');
            }
        }

        $initiative=InitiativePushModel::field('id,title,wt_id,data')->order('id desc')->limit(10)->select();
        $sendCount=InitiativePushModel::whereDay("create_time")->count();
        $WebSiteTemplate=WechatTemplate::select();
        View::assign('WebSiteTemplate', $WebSiteTemplate);
        View::assign('initiative', $initiative);
        View::assign('sendCount', $sendCount);
        return View::fetch();
    }

    /**
     * 获取粉丝数量
     *
     * @Author: hhm <huanghemao@xycms.com>
     * @DateTime: 2022/3/17 0017 下午 12:00
     * @return \think\response\Json
     * @throws Exception
     */
    public function getFansForMP(){
        // $redisConfig=config('cache.stores.redis');
        // $redis=new Redis($redisConfig);
        // $ret=$redis->lpush("{$redisConfig['prefix']}workCallback-test", json_encode([time()],JSON_UNESCAPED_UNICODE));
        $token = WechatHelper::GetWeiXinToken();
        $fansGroup=URL::get_contents("https://api.weixin.qq.com/cgi-bin/tags/get?access_token={$token['access_token']}");
        //获取当前公众号粉丝数量
        // $wxUser=URL::get("https://api.weixin.qq.com/cgi-bin/user/get",['next_openid'=>'',"access_token"=>$token['access_token']]);
        $wxUser=URL::get("https://api.weixin.qq.com/cgi-bin/user/get?access_token={$token['access_token']}");
        $wxUser=json_decode($wxUser,true);
        // dd($wxUser);
        if (!empty($wxUser['errcode']) && $wxUser['errcode']==48001){
            return $this->ajaxReturn("当前公众号接口未授权，请到微信开发平台授权", -100);
        }
//        Cache::set("fansUser",$wxUser);

        $appid=ConfigModel::field('value')->where('ctype','xy_wechatminiprogram')->getByKey('appid');
        $url=ConfigModel::field('value')->where('ctype','web')->getByKey('h5');
        $fansTotal=is_numeric($wxUser['total'])?$wxUser['total']:-1;
        $da['fansGroup']=$fansGroup;
        $da['fansTotal']=$fansTotal;
        $da['appid']=$appid->value;
        $da['url']=$url->value;
        return $this->ajaxReturn("获取成功", 0,$da);
    }




    /**
     * @Notes:获取已发送的模板通知
     * @Author: hhm <huanghemao@exinyun.com>
     * @DateTime: 2022/3/1 0001 下午 15:07
     * @return \think\response\Json
     */
    public function getInitiativeNotify(){
        $G = request()->get();
        $data=InitiativePushModel::order('id', 'desc')->paginate($G['pageSize']);
        return $this->ajaxReturn('获取成功', 0, $data);
    }
}
